package com.ttc.mBackup.BackupContacts;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;


import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;

public class FileProvider {
	public static Boolean writeFileToSDCard(ContactBackup contactBackup, String fileName){

		boolean result = true;

		try {
			// create json string - this is contacts data
			JsonMaker jMaker = new JsonMaker();
			String jsonString = jMaker.toJSONString(contactBackup);
			Log.i("contact", jsonString);

			
			File f = new File(Environment.getExternalStorageDirectory()
					.toString(), fileName);
			FileWriter fw;
			try {
				fw = new FileWriter(f);

				fw.write(jsonString);
				fw.flush();
				fw.close();
				Log.i("contact", "Saved file " + fileName + " to sd card");
			} catch (IOException e1) {
				Log.i("contact", "Error: " + e1.getMessage());
				e1.printStackTrace();
				result = false;
			}
		} catch (Exception e) {
			Log.e("contact", e.getMessage());
			result = false;
		}
		return result;
	}
	
	public static ArrayList<File> getBackupFiles() {
		ArrayList<File>listFiles=new ArrayList<File>();
		File[] files = null;
		try {
			String dirPath = Environment.getExternalStorageDirectory()
					.toString();
					
			File dir = new File(dirPath);
			files = dir.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					// TODO Auto-generated method stub
					return filename.endsWith(".json");
				}
			});

		} catch (Exception e) {
			Log.e("Files in Sdcard", "Error at FileProvider.getbackupFiles: "
					+ e.getMessage());
		}
		Log.i("Number of files", "" + files.length);
		for(int i=0;i<files.length;i++){
			File file=files[i];
			listFiles.add(file);
		}
		Log.i("ListFiles size", "" + listFiles.size());
		
		return listFiles;
	}
}
